package com.itheima.restkeeper.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.restkeeper.AffixFace;
import com.itheima.restkeeper.ApicertFace;
import com.itheima.restkeeper.basic.ResponseWrap;
import com.itheima.restkeeper.enums.ApicertEnum;
import com.itheima.restkeeper.exception.ProjectException;
import com.itheima.restkeeper.req.AffixVo;
import com.itheima.restkeeper.req.ApicertVo;
import com.itheima.restkeeper.utils.EmptyUtil;
import com.itheima.restkeeper.utils.ExceptionsUtil;
import com.itheima.restkeeper.utils.ResponseWrapBuild;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName ApicertController.java
 * @Description 证书Controller
 */
@RestController
@RequestMapping("apicert")
@Slf4j
@Api(tags = "证书controller")
public class ApicertController {

    @DubboReference(version = "${dubbo.application.version}",check = false, timeout = 900000)
    ApicertFace apicertFace;

    @DubboReference(version = "${dubbo.application.version}",check = false, timeout = 900000)
    AffixFace affixFace;

    /**
     * @Description 证书列表
     * @param apicertVo 查询条件
     * @return
     */
    @PostMapping("page/{pageNum}/{pageSize}")
    @ApiOperation(value = "分页查询证书",notes = "分页查询证书")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "apicertVo",value = "证书查询对象",required = true,dataType = "ApicertVo"),
            @ApiImplicitParam(paramType = "path",name = "pageNum",value = "页码",dataType = "Integer"),
            @ApiImplicitParam(paramType = "path",name = "pageSize",value = "每页条数",dataType = "Integer")
    })
    public ResponseWrap<Page<ApicertVo>> findApicertVoPage(
            @RequestBody ApicertVo apicertVo,
            @PathVariable("pageNum") int pageNum,
            @PathVariable("pageSize") int pageSize) throws ProjectException {
        try {
            Page<ApicertVo> apicertVoPage = apicertFace.findApicertVoPage(apicertVo, pageNum, pageSize);
            //处理附件
            if (!EmptyUtil.isNullOrEmpty(apicertVoPage)&&
                    !EmptyUtil.isNullOrEmpty(apicertVoPage.getRecords())){
                List<ApicertVo> apicertVoList = apicertVoPage.getRecords();
                apicertVoList.forEach(n->{
                    List<AffixVo> affixVoList = affixFace.findAffixVoByBusinessId(n.getId());
                    if (!EmptyUtil.isNullOrEmpty(affixVoList)){
                        n.setAffixVo(affixVoList.get(0));
                    }
                });
                apicertVoPage.setRecords(apicertVoList);
            }
            return ResponseWrapBuild.build(ApicertEnum.SUCCEED,apicertVoPage);
        } catch (Exception e) {
            log.error("查询证书列表异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(ApicertEnum.PAGE_FAIL);
        }
    }


    /**
     * @Description 保存证书
     * @param apicertVo 对象信息
     * @return
     */
    @PostMapping
    @ApiOperation(value = "注册证书",notes = "注册证书")
    @ApiImplicitParam(name = "apicertVo",value = "证书对象",required = true,dataType = "ApicertVo")
    ResponseWrap<ApicertVo> createApicert(@RequestBody ApicertVo apicertVo) throws ProjectException {
        try {
            ApicertVo apicertVoResult = apicertFace.createApicert(apicertVo);
            //绑定附件
            if (!EmptyUtil.isNullOrEmpty(apicertVoResult)){
                affixFace.bindBusinessId(
                        AffixVo.builder()
                                .businessId(apicertVoResult.getId())
                                .id(apicertVo.getAffixVo().getId())
                                .build());
            }
            apicertVoResult.setAffixVo(AffixVo.builder()
                    .pathUrl(apicertVo.getAffixVo().getPathUrl())
                    .businessId(apicertVoResult.getId())
                    .id(apicertVo.getAffixVo().getId()).build());
            return ResponseWrapBuild.build(ApicertEnum.SUCCEED,apicertVoResult);
        } catch (Exception e) {
            log.error("保存证书异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(ApicertEnum.CREATE_FAIL);
        }
    }

    /**
     * @Description 修改证书
     * @param apicertVo 对象信息
     * @return
     */
    @PatchMapping
    @ApiOperation(value = "修改证书",notes = "修改证书")
    @ApiImplicitParam(name = "apicertVo",value = "证书对象",required = true,dataType = "ApicertVo")
    ResponseWrap<Boolean> updateApicert(@RequestBody ApicertVo apicertVo) throws ProjectException {
        if (EmptyUtil.isNullOrEmpty(apicertVo.getId())){
            throw new ProjectException(ApicertEnum.UPDATE_FAIL);
        }
        try {
            Boolean flag = apicertFace.updateApicert(apicertVo);
            if (flag){
                List<AffixVo> affixVoList = affixFace.findAffixVoByBusinessId(apicertVo.getId());
                List<Long> affixIds = affixVoList.stream().map(AffixVo::getId).collect(Collectors.toList());
                if (!affixIds.contains(apicertVo.getAffixVo().getId())){
                    //删除证书
                    flag = affixFace.deleteAffixVoByBusinessId(apicertVo.getId());
                    //绑定新证书
                    affixFace.bindBusinessId(AffixVo.builder()
                            .businessId(apicertVo.getId())
                            .id(apicertVo.getAffixVo().getId())
                            .build());
                }
            }
            return ResponseWrapBuild.build(ApicertEnum.SUCCEED,flag);
        } catch (Exception e) {
            log.error("保存证书异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(ApicertEnum.UPDATE_FAIL);
        }
    }

    /**
     * @Description 删除证书
     * @param apicertVo 查询对象
     * @return
     */
    @DeleteMapping
    @ApiOperation(value = "删除证书",notes = "删除证书")
    @ApiImplicitParam(name = "apicertVo",value = "证书查询对象",required = true,dataType = "ApicertVo")
    ResponseWrap<Boolean> deleteApicert(@RequestBody ApicertVo apicertVo ) throws ProjectException {
        String[] checkedIds = apicertVo.getCheckedIds();
        if (EmptyUtil.isNullOrEmpty(checkedIds)){
            throw new ProjectException(ApicertEnum.DELETE_FAIL);
        }
        try {
            Boolean flag = apicertFace.deleteApicert(checkedIds);
            //删除证书
            for (String checkedId : checkedIds) {
                affixFace.deleteAffixVoByBusinessId(Long.valueOf(checkedId));
            }
            return ResponseWrapBuild.build(ApicertEnum.SUCCEED,flag);
        } catch (Exception e) {
            log.error("删除证书异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(ApicertEnum.DELETE_FAIL);
        }
    }

    /**
     * @Description 查找证书
     * @param apicertId 登录名
     * @return
     */
    @GetMapping("{apicertId}")
    @ApiOperation(value = "查找证书",notes = "查找证书")
    @ApiImplicitParam(paramType = "path",name = "apicertId",value = "证书Id",dataType = "Long")
    ResponseWrap<ApicertVo> findApicertByApicertId(@PathVariable("apicertId") Long apicertId) throws ProjectException {

        if (EmptyUtil.isNullOrEmpty(apicertId)){
            throw new ProjectException(ApicertEnum.SELECT_APICERT_FAIL);
        }
        try {
            ApicertVo apicertVo = apicertFace.findApicertByApicertId(apicertId);

            if (apicertVo == null || "NO".equals(apicertVo.getEnableStatus()) || "NO".equals(apicertVo.getEnableFlag())) {
                throw new ProjectException(ApicertEnum.SELECT_APICERT_FAIL);
            }
            // 证书对应附件
            List<AffixVo> affixVoList = affixFace.findAffixVoByBusinessId(apicertVo.getId());
            if (!EmptyUtil.isNullOrEmpty(affixVoList)) {
                AffixVo affixVo = affixVoList.get(0);
                apicertVo.setAffixVo(affixVo);
            }
            return ResponseWrapBuild.build(ApicertEnum.SUCCEED,apicertVo);
        } catch (Exception e) {
            log.error("查找证书所有证书异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(ApicertEnum.SELECT_APICERT_FAIL);
        }
    }

    @PostMapping("update-apicert-enableFlag")
    @ApiOperation(value = "修改证书状态",notes = "修改证书状态")
    @ApiImplicitParam(name = "apicertVo",value = "证书查询对象",required = true,dataType = "ApicertVo")
    ResponseWrap<Boolean> updateApicertEnableFlag(@RequestBody ApicertVo apicertVo) throws ProjectException {
        try {
            Boolean flag = apicertFace.updateApicert(apicertVo);



            return ResponseWrapBuild.build(ApicertEnum.SUCCEED,flag);
        } catch (Exception e) {
            log.error("修改证书状态：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(ApicertEnum.UPDATE_FAIL);
        }
    }

}
